//封装渲染页面
var sArr = [];
function render(data){
    var html = template('slidesTpl', { data: data });
    $('#slidesBox').html(html)
}
//获取轮播图列表
$.ajax({
    type: 'get',
    url: '/slides',
    success: function(response) {
        sArr = response
        render(sArr)
    }
})
//上传轮播图图片
$('#image').on('change', function() {
    var file = this.files[0];
    var formData = new FormData()
    formData.append('avatar', file);
    $.ajax({
        type: 'post',
        url: '/upload',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            $('#hiddenAvatar').val(response[0].avatar)
            $('#showimage').attr('src',response[0].avatar).show()
        }
    })
});
//添加轮播图
$('#slidesForm').on('submit', function() {
    var formData = $(this).serialize()
    $.ajax({
        type: 'post',
        url: '/slides',
        data: formData,
        success: function(response) {
            sArr.push(response)
            render(sArr)
        }
    })
    return false;
})
//删除轮播图
$('#slidesBox').on('click', '.delete', function() {
    if (confirm('确认删除这个轮播图？')) {
        var id = $(this).data('id');
        $.ajax({
            type: 'delete',
            url: '/slides/' + id,
            success: function(response) {
            var index = sArr.findIndex(item => item._id == id)
            sArr.splice(index,1)
            render(sArr)
            }
        })
    }
})

